package com.orange.controller;


import com.orange.commons.Constant;
import com.orange.commons.Result;
import com.orange.domain.User;
import com.orange.service.UserService;
import com.orange.utils.MD5Util;
import com.orange.utils.WebMvcUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Emp
 * @projectName: crm
 * @package: com.powernode.controller
 * @className: LoginController
 * @description: TODO
 * @date: 2021/11/29 13:11
 * @version: 1.0
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 登录功能,查询用户名与MD5密码
     * @param username
     * @param password
     * @param captcha
     * @return
     */
    @RequestMapping("doLogin.do")
    public Result doLogin(String username, String password, String captcha){
        Object code = WebMvcUtil.getSession().getAttribute(Constant.CAPTCHA_CODE);
        if (code.equals(captcha)){
            User user = userService.login(username, MD5Util.md5(password));
            if (null==user){
                return new Result(-1,"用户名或密码不存在");
            }
            //登陆成功,保存登录用户到Session
            user.setPassword(null);
            WebMvcUtil.getSession().setAttribute(Constant.SESSION_USER_KEY,user);
            return new Result(200,"登陆成功");
        }else {
            return new Result(-1,"验证码不正确");
        }
    }

    @RequestMapping("loginOut.do")
    public Result loginOut(){
        try {
            WebMvcUtil.getSession().invalidate();
            return new Result(200,"退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1,"退出登录失败");
        }
    }
}
